package ldh.maker.util;

import javafx.scene.control.TreeItem;
import ldh.maker.constants.TreeNodeTypeEnum;
import ldh.maker.vo.TreeNode;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;

/**
 * Created by ldh on 2017/2/26.
 */
public class FileUtil {

    public static String loadJarFile(String file) throws Exception {
        InputStream inputStream = FileUtil.class.getResourceAsStream(file);
        String data = loadFile(inputStream);
        inputStream.close();
        return data;
    }

    public static String loadFile(InputStream inputStream) throws Exception {
        int size = inputStream.available();
        byte[] data = new byte[size];
        int l = inputStream.read(data);
        return new String(data, "utf-8");
    }

    public static String getSourceRoot() {
        return System.getProperty("user.dir") + "/";
    }

    public static void loadFileTree(String dir, TreeItem<TreeNode> root, boolean isExpand) {
        File file = new File(dir);
        File[] files = file.listFiles();
        if (files == null) return;
        for (File f : files) {
            TreeNodeTypeEnum type = TreeNodeTypeEnum.ITEM;
            if (f.isFile() && (f.getName().endsWith(".java") || f.getName().endsWith(".xml") ||
                f.getName().endsWith(".jsp") || f.getName().endsWith(".css") || f.getName().endsWith(".js") || f.getName().endsWith(".vue") ||
                    f.getName().endsWith(".fxml") || f.getName().endsWith(".json") || f.getName().endsWith(".ftl") || f.getName().endsWith(".tag")
                    || f.getName().endsWith(".properties") || f.getName().endsWith(".dart"))) {
                type = TreeNodeTypeEnum.JAVA_FILE;
            }
            TreeNode tn = new TreeNode(type, f.getName(), root.getValue());
            tn.setData(f.getPath());
            TreeItem<TreeNode> c = new TreeItem<>(tn);
            root.getChildren().add(c);
            loadFileTree(f.getPath(), c, false);
        }
        root.setExpanded(isExpand);
    }

    public static String loadFile(String file) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8);
        StringBuilder sb = new StringBuilder();
        for(String line : lines){
            sb.append(line).append("\r\n");
        }
        return sb.toString();
    }

    public static void saveFile(String file, String json) throws IOException {
        Files.write(Paths.get(file), json.getBytes("utf-8"), StandardOpenOption.CREATE);
    }

    public static void main(String[] args) {
        System.out.println(getSourceRoot());
    }
}
